<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="3">
        <el-input
          class="filterInput"
          clearable
          placeholder="请输入分类名称"
          v-model="filterCategoryName"
        >
        </el-input>
        <el-tree
          :highlight-current="true"
          ref="tree"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="selectedCategory"
        ></el-tree>
      </el-col>
      <el-col :span="21">
        <el-form
          :inline="true"
          ref="queryForm"
          :model="query"
          class="queryForm"
        >
          <el-row type="flex" class="row-bg" justify="space-between">
            <!-- 检索表单 -->
            <el-col :span="20">
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="query.name"
                  placeholder="请输入名称"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" @click="querySearchForm"
                  >搜索</el-button
                >
                <el-button icon="el-icon-refresh" @click="resetSearchForm"
                  >重置</el-button
                >
                <el-tag>选中分类：{{ selectedCategoryName }}</el-tag>
              </el-form-item>
            </el-col>
            <!-- 新增按钮 -->
            <el-col :span="4" class="table-tools">
              <el-button
                :disabled="selectedCategoryId == null"
                icon="el-icon-plus"
                @click="openCheckDialog()"
                v-if="hasPermission(permission.save)"
                >{{ "添加" + dialogTitle }}</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :height="maxTableHeight"
        >
          <el-table-column prop="name" label="名称" width="180" />
          <el-table-column prop="image" align="center" label="图片" width="80">
            <template
              slot-scope="scope"
              v-if="scope.row.image != null && scope.row.image != ''"
            >
              <el-image
                style="width: 40px; height: 40px"
                :src="scope.row.image"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="title" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 0" type="danger">下架</el-tag>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <!-- 编辑 -->
              <el-button
                type="text"
                size="medium"
                icon="el-icon-edit"
                @click="openCheckDialog(scope.row)"
                v-if="hasPermission(permission.update)"
              ></el-button>

              <!-- 删除 -->
              <el-button
                type="text"
                size="medium"
                icon="el-icon-delete"
                @click="deleteRow(scope.row)"
                v-if="hasPermission(permission.delete)"
              ></el-button>

              <!-- 描述 -->
              <el-button
                type="text"
                size="medium"
                icon="el-icon-document"
                @click="openDetailDialog(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页标签 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <Update ref="updateDialog" :dialogTitle="dialogTitle"></Update>
    <Detail ref="detailDialog"></Detail>
  </div>
</template>

<script>
import { mapState } from "vuex";
import listMixins from "@/views/base/listMixins";

import Update from "@/views/product/spu/update";
import Detail from "@/views/product/spu/detail";
import productApi from "@/api/productApi";

export default {
  name: "productSpu",
  data() {
    return {
      permission: {
        save: "product:spu:save",
        update: "product:spu:update",
        delete: "product:spu:delete",
      },
      dialogTitle: "商品",
      filterCategoryName: "",
      // 分类树信息
      treeProps: {
        children: "children",
        label: "name",
      },
      // 分类列表数据
      treeData: [],
      // 检索条件
      query: {
        name: "",
        categoryId: null,
      },
      // 选中的分类信息
      selectedCategoryId: null,
      selectedCategoryName: "",
    };
  },
  components: {
    Update,
    Detail,
  },
  mixins: [listMixins],
  created() {
    this.remoteCategoryTreeList();
  },
  watch: {
    filterCategoryName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 打开弹窗前校验分类
    openCheckDialog(row) {
      if (null == row && this.selectedCategoryId != null) {
        // 设置额外数据
        this.$refs["updateDialog"].setMeta({
          categoryId: this.selectedCategoryId,
          categoryName: this.selectedCategoryName,
        });
        this.openDialog();
      } else {
        this.openDialog(row);
      }
    },
    // 打开商品详情弹窗
    openDetailDialog(row) {
      this.$refs["detailDialog"].open(row);
    },
    // 商品分类过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 分类树
    remoteCategoryTreeList() {
      productApi.category
        .treeList()
        .then((res) => {
          this.treeData = res.data;
          this.$nextTick(() => {
            this.expandAll();
          });
        })
        .catch((error) => {});
    },
    // 全部展开
    expandAll() {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].expanded = true;
      }
    },
    // 根据查询条件，检索数据
    querySearchForm() {
      this.remoteTableData();
    },
    // 清空查询条件，检索数据
    resetSearchForm() {
      this.$refs["queryForm"].resetFields();
      this.remoteTableData();
    },
    // 查询商品spu列表数据
    remoteTableData() {
      productApi.spu.listPage(this.searchParams()).then((res) => {
        this.updateTableData(res.data);
      });
    },
    // 选中分类
    selectedCategory(data, node, tree) {
      this.query.categoryId = data.id;
      this.selectedCategoryId = data.id;
      // 获取当前节点所有父级节点
      var parentNodeArr = [];
      var parentNameArr = [];
      this.getParentAll(parentNodeArr, node);
      parentNodeArr.forEach((node, index, arr) => {
        parentNameArr.push(node.data.name);
      });
      parentNameArr.push(data.name);

      // 拼接字符串
      this.selectedCategoryName = parentNameArr.join(" / ");
      this.$nextTick(() => {
        this.remoteTableData();
      });
    },
    // 获取当前节点所有父级节点
    getParentAll(parentNodeArr, node) {
      if (node) {
        // 节点的第一个父级
        var parentNode = node.parent;
        // level为节点的层级 level=1 为顶级节点
        for (var j = 0, lv = node.level; j < lv; j++) {
          if (parentNode.level > 0) {
            // 将所有父级节点放入集合中
            parentNodeArr.push(parentNode);
          }
          // 继续获取父级节点的父级节点
          parentNode = parentNode.parent;
        }

        if (parentNodeArr.length > 1) {
          // 如果集合长度>1 则将数组进行倒叙.reverse() 其是就是将所有节点按照 从 顶级节点 依次往下排
          parentNodeArr.reverse();
        }
      }
    },
    // 删除
    deleteRow(row) {
      this.$confirm("确认删除商品 [" + row.name + "] ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          productApi.spu
            .delete(row.id)
            .then((res) => {
              this.resetSearchForm();
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
  // vuex数据
  computed: mapState({
    user: (state) => state.user.userInfo,
  }),
};
</script>

<style lang="less" scoped>
.filterInput {
  margin-bottom: 15px;
}
.el-tree-node__content {
  height: 32px;
}
.queryForm {
  .el-tag {
    margin-left: 20px;
    height: 40px;
    line-height: 38px;
    font-size: 14px;
  }
}
.spuImage {
  width: 40px;
  height: 40px;
}
</style>